<template>
  <div id="breakon-article-editor" class="bre-height100">
    <a-slider
      style="margin: 0px"
      :min="0"
      :max="24"
      v-model:value="widthInput"
      :disabled="false"
    />
    <!-- <EditorSlider style="width:90%"  @my-emit="parentEmit" ></EditorSlider> -->
    <div class="gadgets-rectangle">
      <div class="gadgets-rectangle2"></div>
      <a-button shape="circle" type="primary" @click="showDrawer"> ☈ </a-button>
    </div>
    <a-drawer
      :title="'文章设置:' + uuid"
      :placement="placement"
      :closable="false"
      :visible="visible"
      width="300px"
      @close="onClose"
    >
      <div style="width: 150px; margin: 0 auto">
        <a-image
          style="width: 100%"
          alt="avatar"
          :src="coverImg"
          fallback=""
        />
        <!-- <a-upload
          v-model:fileList="fileList"
          style="width: 102px"
          name="avatar"
          list-type="picture-card"
          class="avatar-uploader"
          :show-upload-list="false"
          action="https://www.xxx.com"
          :before-upload="beforeUpload"
          @change="handleChange"
        >
          <img
            style="width: 100%"
            v-if="imageUrl"
            :src="imageUrl"
            alt="avatar"
          />
          <div v-else>
            <loading-outlined v-if="loading" />
            <plus-outlined v-else />
            <div class="ant-upload-text">上传封面</div>
          </div>
        </a-upload> -->
      </div>
      <a-row>
        <a-col :span="24">
          <a-col :span="24">
            <details open="open">
              <summary>摘要</summary>
              <div>{{ ArticleForm.excerpt }}</div>
            </details>
            <br />
            封面：
            <a-input
              v-model:value="coverImg"
              style="width: 220px"
              placeholder="网络地址"
            />
          </a-col>
          <br />
          <a-col :span="24">
            状态：
            <!-- @focus="focus" -->
            <a-select
              v-model:value="articleStatus"
              style="width: 220px"
              ref="select"
              @select="draftSetInterval"
            >
              <!-- @change="handleChange" -->
              <a-select-option
                v-for="item in statusRule"
                :key="item"
                :value="item.statu"
              >
                {{ item.name }}
              </a-select-option>
            </a-select>
          </a-col>
          <br />
          <a-col :span="24">
            标签：
            <a-select
              v-model:value="ChangeInputTag"
              mode="tags"
              style="width: 80%"
              placeholder="标签"
              :token-separators="[',']"
              @change="handleChangeInput"
            >
            </a-select>
          </a-col>
          <a-col :span="24">
            <!-- 功能3 -->
          </a-col>
          <a-col :span="4"> </a-col>
          <!-- </center> -->
        </a-col>
      </a-row>
      <br />
      <a-button @click="saveAndUpdate" style="float: right" type="primary">
        保存文章
        <SyncOutlined v-show="ArticleForm.autoSaveInput" spin />
      </a-button>
      <a-button @click="reset" style="float: left" type="primary">
        重置文章
      </a-button>
      <br />
      <br />
    </a-drawer>
    <a-row class="bre-height100">
      <a-col class="bre-height100" :span="widthInput">
        <!-- <div style="border-right: #f0f2f5 solid; min-height:700px"  class="bre-height100" contenteditable="plaintext-only"  
        @keyup="renderingMD"   v-text="inputText"     >
         </div>  -->

        <a-textarea v-model:value="inputText" spellcheck="false" placeholder="输入" auto-size />
      </a-col>
      <a-col :span="24 - widthInput">
        <div
          class="markdown-body"
          @click="clickButt"
          v-html="renderingMD(inputText)"
        ></div>
      </a-col>
    </a-row>
    <a-back-top />
  </div>
</template>
<script>
import md from "./markdwon-it-config";
import { GetFrontMatter } from "./markdwon-it-config";
import { SyncOutlined } from "@ant-design/icons-vue";

import { reactive, ref, onBeforeUnmount } from "vue";
import { useRouter } from "vue-router";
import _statusRule from "./status-rule";
// import { PlusOutlined, LoadingOutlined } from "@ant-design/icons-vue";
import { AddArticle, AuthAccurateFind } from "@/adminCore/api/article";
import "@/assets/css/markdownit-customize.scss";
// import { message } from "ant-design-vue";
import AntComponents from "ant-design-vue";
import { injectionEvent } from "@/utils/editMarkdown";
// function getBase64(img, callback) {
//   const reader = new FileReader();
//   reader.addEventListener("load", () => callback(reader.result));
//   reader.readAsDataURL(img);
// }

export default {
  data() {
    return {
      placement: "right",
      fileList: [],
      statusRule: _statusRule,
    };
  },
  components: {
    SyncOutlined,
    // Menu,
  },

  setup() {
    let ArticleForm = reactive({
      status: _statusRule[1].statu,
      guid: 0,
      content: "",
      title: "",
      contentHTML: "",
      coverImg: "",
      excerpt: "",
      autoSaveInput: false,
    });
    let coverImg = ref(""); //xxx
    const $router = useRouter();
    // const route = useRoute()
    // let tagGroupMap="" //获取到的标签名字
    let ChangeInputTag = ref([]);
    const initText = `---\ntitle:\n---`;
    let inputText = ref(initText);
    let uuid = ref(0);
    if ($router.currentRoute.value.query.id) {
      uuid.value = Number($router.currentRoute.value.query.id);
      AuthAccurateFind({ guid: String(uuid.value) }).then(({ data }) => {
        inputText.value = data.content;
        articleStatus.value = data.status;
        coverImg.value = data["coverImg"] ? data.coverImg : "";
        ArticleForm.excerpt = data["excerpt"] ? data.excerpt : "";
        if (data.tagGroupID && data.tagGroupID.length > 0) {
          ChangeInputTag.value = data.tagGroupID.map((item) => item.name);
        }
      });
    }

    //修改变化
    function renderingMD(v = "") { 
      let data=md.render(v)
      return data 
    }
    //上传图片
    let loading = ref(false);
    let imageUrl = ref("");
    // function handleChange(info) {
    //   if (info.file.status === "uploading") {
    //     loading.value = true;
    //     return;
    //   }
    //   if (info.file.status === "done") {
    //     getBase64(info.file.originFileObj, (imageUrls) => {
    //       imageUrl.value = imageUrls;
    //       loading.value = false;
    //     });
    //   }
    //   if (info.file.status === "error") {
    //     loading.value = false;
    //   }
    // }
    // function beforeUpload(file) {
    //   const isJpgOrPng =
    //     file.type === "image/jpeg" || file.type === "image/png";
    //   if (!isJpgOrPng) {
    //     AntComponents.message.error("You can only upload JPG file!");
    //   }
    //   const isLt2M = file.size / 1024 / 1024 < 2;
    //   if (!isLt2M) {
    //     AntComponents.message.error("Image must smaller than 2MB!");
    //   }
    //   return isJpgOrPng && isLt2M;
    // }

    // 打开和关闭

    let visible = ref(false);
    let showDrawer = () => (visible.value = true);
    let onClose = () => (visible.value = false); 
    // //注入事件
    function clickButt(event, reset = "reset") { 
     injectionEvent(event, reset);
    }

    function saveAndUpdate() {
      let str = inputText.value;
      let html = renderingMD(str);
      if (!GetFrontMatter["title"] || GetFrontMatter["title"].length == 0) {
        AntComponents.message.warn("标题格式出错");
        return;
      }

      ArticleForm = {
        guid: uuid.value,
        title: GetFrontMatter.title,
        typeGroup: ChangeInputTag.value,
        content: str,
        contentHTML: html,
        status: articleStatus.value,
        coverImg: coverImg.value,
      };
      AddArticle(ArticleForm).then(({ data }) => {
        if (data.code == 1000 && uuid.value == 0) {
          AntComponents.message.info("文章添加成功");
          uuid.value = data.data;
        } else if (data.code == 1000 && uuid.value >= 0) {
          AntComponents.message.info("文章修改成功");
        } else {
          AntComponents.message.info(data.msg);
        }
      });
    }

    function reset() {
      ArticleForm = {
        status: _statusRule[1].statu,
        guid: 0,
        content: "",
        title: "",
        contentHTML: "",
        coverImg: "",
        excerpt: "",
      };
      uuid.value = 0;
      inputText.value = initText + "\n" + inputText.value;
      ChangeInputTag.value = [];
    }
    //
    let widthInput = ref(12);
    // let ChangeInputTag = reactive(
    // [{ name: "其他", id: "" }]);
    function handleChangeInput(value) {
      console.log(value);
    }
    let articleStatus = ref(_statusRule[1].statu);
    let sendAuto;
    function draftSetInterval(data) {
      if (data == "draft") {
        AntComponents.message.info("自动保存开启");
        ArticleForm.autoSaveInput = true;
        sendAuto = setInterval(function () {
          ArticleForm.autoSaveInput = true;
          saveAndUpdate();
        }, 10000); //10秒保存一次
      } else {
        clearSendAuto();
      }
    }
    function clearSendAuto() {
      ArticleForm.autoSaveInput = false;
      clearInterval(sendAuto);
    }

    onBeforeUnmount(() => {
      clearSendAuto();
    });
    return {
      ArticleForm, //文章表
      coverImg,
      uuid,
      inputText,
      renderingMD,
      loading,
      imageUrl,
      // handleChange,
      // beforeUpload,
      visible,
      showDrawer,
      onClose,
      clickButt,
      widthInput,
      saveAndUpdate,
      reset,
      handleChangeInput,
      ChangeInputTag,
      articleStatus,
      draftSetInterval,
    };
  },
};
</script>
<style lang="scss" scop >
#breakon-article-editor {
  .avatar-uploader > .ant-upload {
    width: 128px;
    height: 128px;
  }
  .ant-upload-select-picture-card i {
    font-size: 32px;
    color: #999;
  }
  [contenteditable]:focus {
    outline: rgba(24, 144, 255, 0.12) solid;
  }
  .ant-upload-select-picture-card .ant-upload-text {
    margin-top: 8px;
    color: #666;
  }

  .gadgets-rectangle {
    width: 33px;
    height: auto;
    position: fixed;
    right: 40px;
    z-index: 1;
    top: 15%;
  }
  .gadgets-rectangle2 {
    height: 10px;
    width: 80px;
    border-radius: 20%;
    background: #1890ff;
    margin-bottom: -20px;
  }
}

.ant-drawer-body {
  padding: 15px;
}
</style>